package com.wujie.activies.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.wujie.activies.ConfigManage;
import com.wujie.activies.controller.exchangeBean.JSONData;
import com.wujie.activies.controller.exchangeBean.JSONPageData;
import com.wujie.activies.controller.exchangeBean.PageParamBean;
import com.wujie.activies.model.Activity;
import com.wujie.activies.model.ActivityType;
import com.wujie.activies.model.Contact;
import com.wujie.activies.service.*;
import com.wujie.activies.service.IContactService;
import com.wujie.activies.service.helper.IReadMikeExcels;
import com.wujie.activies.service.helper.imp.ReadMikeExcelsImpl;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by 晒太阳的鱼 on 2015/12/22.
 */
@Controller("activiescontroller")
@RequestMapping("/rest/act/")
public class RestActivitiesController {
    private static Logger TRACE = LoggerFactory.getLogger(RestActivitiesController.class);
    @Resource
    private IActivityTypeService activityTypeService;
    @Resource
    private IActivityService activityService;
    @Resource
    private IContactService contactService;

    //获取所有的活动类型
    @RequestMapping("actstp")
    @ResponseBody
    public String getActivitiesType() {
        return JSON.toJSONString(activityTypeService.getAll());
    }

    //获取指定类型的所有活动
    @RequestMapping("actintp")
    @ResponseBody
    public String getActivityInType(Integer id, PageParamBean pagiBean) {
        ActivityType activityType = new ActivityType();
        activityType.setId(id);
        PageHelper.startPage(pagiBean.getCurr(), pagiBean.getLimit());
        List<Activity> rs = new ArrayList<>();
        if(id == -1){
             rs = activityService.getAll();
        }else{
//             rs = activityTypeService.getByInstance(activityType);
        }

        String jsonstr = new JSONPageData(rs).toString();
        return jsonstr;
    }

    //通过活动类型ID 获取所有参加的联系人
    @RequestMapping("actct")
    @ResponseBody
    public String getContactsByActivityID(Integer id, PageParamBean pagiBean) {

        PageHelper.startPage(pagiBean.getCurr(), pagiBean.getLimit());
        List<Contact> rs = new ArrayList<>();
        if(id == -1){
            rs = contactService.getAll();
        }else{
//            rs = activityContactService.getByInstance(at);
        }
        return new JSONPageData(rs).toString();
    }

    //上传麦克导出的excel文件
    @RequestMapping("upmkxls")
    @ResponseBody
    public String uploadMikeExcel(@RequestParam(value = "file1") MultipartFile file) {
        JSONData retVal = new JSONData();

        StringBuilder sb = new StringBuilder();
        sb.append(ConfigManage.getProp("filebasepath").toString())
                .append(ConfigManage.getProp("mikexlspath").toString());
        File baseDic = new File(sb.toString());
        if (!baseDic.exists()) {
            try {
                FileUtils.forceMkdir(baseDic);
            } catch (IOException e) {
                TRACE.error("创建文件保存目录失败", e);
                retVal.setCode(-1);
                retVal.setDesc("创建文件保存目录失败");
                return retVal.toString();
            }
        }

        sb.append(file.getOriginalFilename());
        File mikefile = new File(sb.toString());

        try {
            if (!mikefile.exists()) {
                mikefile.createNewFile();
            }
            if(mikefile.exists()){
                mikefile.delete();
                mikefile.createNewFile();
            }
            FileUtils.writeByteArrayToFile(mikefile,file.getBytes(),false);
        } catch (IOException e) {
            TRACE.error("保存上传的麦克excel出错 ", e);
            retVal.setCode(-1);
            retVal.setDesc("保存上传的麦克excel出错");
            return retVal.toString();
        }
        IReadMikeExcels iReadMikeExcels = new ReadMikeExcelsImpl();
        try {
            Map<String, Object> exceldt = iReadMikeExcels.getExcelData(mikefile);
            String activitynm = exceldt.get("activityname").toString();
            String activitytpnm = exceldt.get("activitytype").toString();

            List<Contact> contacts = (List<Contact>) exceldt.get("contacts");
            ActivityType at = new ActivityType();
            at.setName(activitytpnm);

            //插入活动类型
            List<ActivityType> ats = activityTypeService.getAll();
            if (ats.isEmpty() || ats == null) {
                activityTypeService.insertSelective(at);
            }else{
                at = ats.get(0);
            }
            int actyid = at.getId();
            if( actyid <= 0){
                retVal.setCode(-1);
                retVal.setDesc("插入数据时无法获取保存的活动类型ID，关联联系人和活动失败");
                return retVal.toString();
            }

            //插入活动
            Activity activity = new Activity();
            activity.setName(activitynm);
//            activity.setTypeId(actyid);
            List<Activity> as = activityService.getAll();
            if (as.isEmpty() || as == null) {
                activityService.insertSelective(activity);
            }else{
                activity = as.get(0);
            }
            int activityid = activity.getId();
            if( activityid <= 0){
                retVal.setCode(-1);
                retVal.setDesc("插入数据时无法获取保存的活动ID，关联联系人和活动失败");
                return retVal.toString();
            }
         /*   ActivityContact activityContact = new ActivityContact();
            activityContact.setActivityId(activityid);
            activityContact.setActivityTypeId(actyid);
            //插入联系人
            for (Contact contact : contacts) {
                contactService.insertSelective(contact);
                //关联联系人和活动
                activityContact = new ActivityContact();
                activityContact.setActivityId(activityid);
                activityContact.setActivityTypeId(actyid);
                activityContact.setContactId(contact.getId());
                activityContactService.insertSelective(
                        activityContact);
            }*/
            retVal.setCode(1);
            retVal.setDesc("保存成功");
        } catch (Exception e) {
            retVal.setCode(-1);
            retVal.setDesc("保存上传的excel文件数据失败");
            TRACE.error("保存上传的excel文件数据失败，原因: ", e);
            return retVal.toString();
        }
        return retVal.toString();
    }
}

